package com.tinusgraglin.enclusiv.ui.screens

import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.tinusgraglin.enclusiv.R
import com.tinusgraglin.enclusiv.datalayer.Exceptions.*
import com.tinusgraglin.enclusiv.ui.EnclusivViewModelFactory
import com.tinusgraglin.enclusiv.ui.viewmodel.SignInActivityViewModel
import com.tinusgraglin.enclusiv.ui.components.EmailField
import com.tinusgraglin.enclusiv.ui.components.FantasticCircularButtonWithLoadingIndicator
import com.tinusgraglin.enclusiv.ui.components.PasswordField
import com.tinusgraglin.enclusiv.ui.components.SimpleConfirmAlertDialog
import com.tinusgraglin.enclusiv.ui.theme.*
import kotlinx.coroutines.launch

@OptIn(ExperimentalComposeUiApi::class)
class SignInActivity : ComponentActivity() {
    private val viewModel: SignInActivityViewModel by viewModels {
        EnclusivViewModelFactory()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            EnclusivTheme {
                SignInScreen()
            }
        }
    }

    @Preview
    @Composable
    fun SignInScreen() {
        val keyboardController = LocalSoftwareKeyboardController.current

        var email by rememberSaveable { mutableStateOf(viewModel.refUserEmailStored ?: "") }
        var password by rememberSaveable { mutableStateOf(viewModel.refUserPasswordStored ?: "") }
        var rememberFields by rememberSaveable { mutableStateOf(viewModel.refRememberUser) }
        var isSigningIn by rememberSaveable { mutableStateOf(false) }
        var showAlert by rememberSaveable { mutableStateOf(false) }
        var alertMsg by rememberSaveable { mutableStateOf("") }

        val pwdFieldFocusRequester = FocusRequester()
        val scope = rememberCoroutineScope()

        val onGoClicked = {
            isSigningIn = true

            scope.launch {
                val deferred = viewModel.loginAsync(email, password)
                try {
                    val userData = deferred.await()
                    viewModel.refUserEmailStored = email
                    if (rememberFields)
                        viewModel.refUserPasswordStored = password
                    else
                        viewModel.refUserPasswordStored = null

                    val intent = Intent(this@SignInActivity, MainActivity::class.java)
                    startActivity(intent)
                } catch (une: UserNotFound) {
                    showAlert = true
                    alertMsg = getString(R.string.msg_account_not_found_verbose)
                } catch (wpe: WrongPassword) {
                    showAlert = true
                    alertMsg = getString(R.string.msg_check_password)
                } catch (e: Exception) {
                    showAlert = true
                    alertMsg = getString(R.string.msg_abnormal_exception)
                } finally {
                    isSigningIn = false
                }
            }
        }

        val onSignUpClicked = {
            val intent = Intent(this@SignInActivity, SignUpActivity::class.java)
            startActivity(intent)
        }

        Surface(
            modifier = Modifier.fillMaxSize(),
            color = MaterialTheme.colors.background
        ) {
            Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.align(
                    Alignment.TopCenter)) {
                    Spacer(modifier = Modifier.height(100.dp))
                    Image(painter = painterResource(id = R.drawable.logo_ocean_of_fantasy_256),
                        contentDescription = null, modifier = Modifier.size(100.dp))
                }

                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                    EmailField(
                        value = email,
                        onValueChange = { email = it },
                        enabled = !isSigningIn,
                        modifier = Modifier
                            .fillMaxWidth(0.8F)
                            .wrapContentHeight(),
                        textStyle = TextFieldStyle,
                        onKeyBoardActionDone = {
                            pwdFieldFocusRequester.requestFocus()
                        }
                    )

                    Spacer(modifier = Modifier.height(10.dp))

                    PasswordField(
                        value = password,
                        onPasswordValueChange = {
                            password = it
                        },
                        enabled = !isSigningIn,
                        textStyle = TextFieldStyle,
                        modifier = Modifier
                            .fillMaxWidth(0.8F)
                            .wrapContentHeight()
                            .focusRequester(pwdFieldFocusRequester),
                        onKeyBoardActionDone = {
                            keyboardController?.hide()
                        }
                    )

                    Spacer(modifier = Modifier.height(30.dp))

                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Checkbox(
                            checked = rememberFields,
                            onCheckedChange =
                            {
                                rememberFields = it
                                viewModel.refRememberUser = it
                            },
                            enabled = !isSigningIn,
                            modifier = Modifier
                                .size(25.dp)
                                .padding(2.dp),
                            colors = CheckboxDefaults.colors(
                                uncheckedColor = PurpleMain
                            )
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(
                            text = stringResource(R.string.ui_checkbox_remember_me),
                            fontSize = 14.sp,
                            textAlign = TextAlign.Center
                        )
                    }
                }

                Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.align(
                    Alignment.BottomCenter)) {
                    FantasticCircularButtonWithLoadingIndicator(
                        textStr = "Go",
                        onClick = { onGoClicked() },
                        isLoading = isSigningIn,
                        enabled = email.isNotEmpty() && password.isNotEmpty() && !isSigningIn
                    )

                    Spacer(modifier = Modifier.height(30.dp))

                    ClickableText(
                        text = AnnotatedString(stringResource(R.string.ui_sign_up)),
                        onClick = { onSignUpClicked() },
                        style = TextStyle(color = BlueMain, fontSize = 16.sp)
                    )

                    Spacer(modifier = Modifier.height(50.dp))
                }
            }

            if (showAlert) {
                SimpleConfirmAlertDialog(msg = alertMsg) {
                    showAlert = false
                }
            }
        }
    }
}